/*
 * Win32.cs
 * 
 * Error-safe managed wrappers for Win32 API functions.
 */
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace Jitsu
{
    internal class Win32
    {
        //
        // Interface

        public static void SetConsoleColor(ConsoleColorFlags colorFlags)
        {
            // Set the color on the current stdout stream.
            const int stdout = -11;

            IntPtr hStdOut = Kernel32.GetStdHandle(stdout);
            if (hStdOut == IntPtr.Zero || hStdOut == new IntPtr(-1))
                throw new Win32Exception();

            if (!Kernel32.SetConsoleTextAttribute(hStdOut, colorFlags))
                throw new Win32Exception();
        }

        public static void TrySetConsoleColor(ConsoleColorFlags colorFlags)
        {
            // SetConsoleTextAttribute may fail if stdout is redirected to a sink other 
            // than the cmd window (eg: VS's output window).
            try
            { SetConsoleColor(colorFlags); }
            catch (Win32Exception)
            { }
        }

        [Flags]
        public enum ConsoleColorFlags : ushort
        {
            ForegroundBlue = 1,
            ForegroundGreen = 2,
            ForegroundRed = 4,
            ForegroundGray = 7,
            ForegroundIntense = 8,
            BackgroundBlue = 16,
            BackgroundGreen = 32,
            BackgroundRed = 64,
            BackgroundIntense = 128
        }

        //
        // Implementation

        private class Kernel32
        {
            [DllImport("Kernel32.dll", SetLastError = true)]
            public static extern IntPtr GetStdHandle(int nStdHandle);

            [DllImport("Kernel32.dll", SetLastError = true)]
            public static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, ConsoleColorFlags wAttributes);
        }
    }
}